import React, { useState, useEffect } from 'react';
import { get_type, CkValue, useCheck, useForm, ck_ascii, ck_empty, Dlg, IkInput } from '../../nui';
import { loc } from '../../local';

const InfoDlg = ({ open, setOpen, hcmd, umd }) => {
    const [open_check, openCheck, hcheck] = useCheck();
    const [value, setValue] = useState();
    const form = useForm(setValue);

    useEffect(() => {
        if (umd.fin === "edit") {
            setValue({
                sn: umd.cur.sn,
                des: umd.cur.des,
            });
        }
        else if (umd.fin === "add") {
            setValue(null);
        }
    }, [umd]);

    const ckdes = {
        sn: loc("zdm"),
        des: loc("ms"),
    };

    const hok = () => {
        const ck = {
            sn: (v) => ck_ascii(v, ckdes.sn),
            des: (v) => ck_empty(v, ckdes.des),
        };

        if (!form.hcheck(ck, value)) {
            return;
        }

        setOpen(false);
        hcmd(value);
    };

    return (
        <Dlg open={open} hcmd={() => hcheck(value, ckdes, hok)} title={loc("pz")} hcancel={() => setOpen(false)}>
            <div className="flex flex-col">
                <IkInput label={ckdes.sn} name="sn" form={form} value={value}/>
                <IkInput label={ckdes.des} name="des" form={form} value={value}/>
            </div>
            <CkValue setOpen={openCheck} open={open_check} value={value} des={ckdes} setValue={setValue} hcmd={hok}/>
        </Dlg>
    );
};

export {get_type, InfoDlg};
